package com.zhuzi.guicollect.controller.fx;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.RequiredFieldValidator;
import com.zhuzi.guicollect.utils.AlertUtils;
import com.zhuzi.guicollect.utils.DateUtils;
import com.zhuzi.guicollect.utils.IniUtils;
import com.zhuzi.guicollect.utils.SysUtils;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid;
import org.kordamp.ikonli.javafx.FontIcon;

import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ResourceBundle;

/**
 * @author MI
 * @ClassName XueQiuController.java
 * @createTime 2022年01月25日 17:13:00
 */
@Slf4j
@FXMLController
public class XueQiuController implements Initializable {
    private static final String ERROR = "error";
    @FXML
    public JFXButton cjBut;

    @FXML
    public JFXTextField textDir;

    @FXML
    public JFXTextField textUrl;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //输入框校验
        RequiredFieldValidator validator = new RequiredFieldValidator();
        validator.setMessage("请输入");
        FontIcon warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
        warnIcon.getStyleClass().add("info");
        validator.setIcon(warnIcon);
        textUrl.getValidators().add(validator);
        textUrl.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                textUrl.validate();
            }
        });

        validator = new RequiredFieldValidator();
        validator.setMessage("存放路径不能为空");
        warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
        warnIcon.getStyleClass().add(ERROR);
        validator.setIcon(warnIcon);
        textDir.getValidators().add(validator);
        textDir.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                textDir.validate();
            }
        });

        //textDir 设置值
        String hisDir = IniUtils.read("default", "dir");
        if (!StringUtils.equals("d:/pic", hisDir) & SysUtils.isDirExit(hisDir)) {
            if (StringUtils.contains(hisDir, "A-jsl")) {
                String[] split = hisDir.split("A-jsl");
                hisDir = split[0] + "D-微信公众号\\07-雪球";
            }
            String finalHisDir = hisDir;
            Platform.runLater(() -> {
                textDir.setText(finalHisDir);
            });
        }


    }

    public void collectArticle(ActionEvent actionEvent) {
        if (!textDir.validate() || !textUrl.validate()) {
            AlertUtils.showNotifications("提示", "请输入", 3, Pos.CENTER_RIGHT);
            return;
        }
        System.out.println(textUrl.validate());
        String path = Paths.get(textDir.getText()).toString();
        cjBut.setDisable(true);
        try {
            String title = cal(path);
            AlertUtils.showNotifications("提示", title + " 采集完成", 3, Pos.BOTTOM_RIGHT);
        } catch (Exception e) {
            log.error("采集号异常", e);
            AlertUtils.showNotifications("提示", "输入错误信息" + e.getLocalizedMessage(), 3, Pos.BOTTOM_RIGHT);
        }
        Platform.runLater(() -> {
            cjBut.setDisable(false);
        });
    }

    private String cal(String path) throws Exception {
        Connection.Response response = Jsoup.connect(textUrl.getText()).method(Connection.Method.GET).execute();
        Document doc = Jsoup.parse(response.body());
        String htmlBody = response.body();
        //原始文章是 //开头的，如果抓取访问就是本地协议https://blog.csdn.net/weixin_42508745/article/details/82628353
        htmlBody = htmlBody.replace("href=\"//", "href=\"https://").replace("src=\"//", "src=\"https://");
        //替换名字，因为可能出现该名字不能创建文件夹
        String title = StringEscapeUtils.unescapeHtml4(doc.getElementsByTag("title").text()).substring(0, 16);
        title = FilenameUtils.getBaseName(textUrl.getText()) + "_" + title.replaceAll("[/\\\\:*?|]", "_").replaceAll("[\"<>]", "'");
        FileUtils.writeStringToFile(Paths.get(path, title + DateUtils.getDateStr() + ".html").toFile(), htmlBody, StandardCharsets.UTF_8);
        return title;
    }
}
